package com.lm56.web.sys.controller;


import com.lm56.common.exception.MyException;
import com.lm56.common.jcaptcha.JCaptcha;
import com.lm56.web.CommonService;
import com.lm56.web.sys.domain.UserForm;
import com.lm56.web.sys.domain.User;
import com.lm56.web.sys.domain.UserContact;
import com.lm56.web.sys.domain.UserDetail;
import com.lm56.web.sys.service.UserService;
import com.lm56.web.network.domain.Location;
import com.lm56.web.network.domain.ShippingType;
import com.octo.captcha.service.CaptchaServiceException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

import com.lm56.common.exception.UserAlreadyExistsException;

/**
 * Created by kelvin on 16/10/24.
 */
@Controller
@RequestMapping(value = "/")
public class RegisterController {

    Logger logger = LoggerFactory.getLogger(RegisterController.class);

    @Autowired
    ShippingTypesCollectionEditor shippingTypesCollectionEditor;

    @Autowired
    UserService userService;

    @Autowired
    CommonService commonService;


    @InitBinder
    public void initBinder(DataBinder binder) {
        binder.registerCustomEditor(List.class, "companyShippingTypes", shippingTypesCollectionEditor);
        binder.setValidator(new RegisterValidator());
    }

    @RequestMapping(value = "register", method = RequestMethod.GET)
    public String registerPage(Model model) {
        List<ShippingType> shippingTypes = commonService.getShippingTypeList();
        logger.debug("shippingTypes", shippingTypes);
        model.addAttribute("shippingTypes", shippingTypes);
        return "register";
    }


    @RequestMapping(value = "register", method = RequestMethod.POST)
    public String doRegister(@Valid UserForm userForm, BindingResult result, Model model, HttpServletRequest request) {


        logger.debug("doRegister; user is:", userForm);


        if (result.hasErrors()) {
            List<ShippingType> shippingTypes = commonService.getShippingTypeList();
            model.addAttribute("shippingTypes", shippingTypes);
            return "register";
        }


        //验证码验证
        String captchaCode = userForm.getCaptchaCode();
        try {
            //验证输入的验证码
            if (!JCaptcha.hasCaptcha(request, captchaCode)) {
                //验证不能过过，抛出异常
                result.rejectValue("captchaCode", null, "验证码不正确");
            }

        } catch (CaptchaServiceException e) {
            e.printStackTrace();
            //发生异常，则作业错误返回页面
            result.rejectValue("captchaCode", null, "验证码不正确");
        }

        if (result.hasErrors()) {
            return "register";
        }

        //组装userDetail
        UserDetail userDetail = new UserDetail();
        userDetail.setPhoneNo(userForm.getPhoneNo());

        userDetail.setPassword(userForm.getPassword());
        userDetail.setEmail(userForm.getEmail());
        int userType = userForm.getUserType();
        userDetail.setUserType(userForm.getUserType()); //1.company;2.sender;3.receiver;4.driver;5.other


        //公司
        if (userType == User.USER_TYPE_COMPANY) {
            userDetail.setLocation(userForm.getCompanyLocation());
            userDetail.setUserName(userForm.getCompanyName());
            userDetail.setUserAddr(userForm.getCompanyAddr());


            List<UserContact> contacts = new ArrayList<UserContact>();
            UserContact userContact = new UserContact();
            userContact.setContactType(UserContact.CONTACT_TYPE_MOBILE_PHONE);
            userContact.setContactName(userForm.getCompanyContactName());
            userContact.setContactAccount(userForm.getCompanyContactPhoneNo());
            contacts.add(userContact);
            //QQ
            if (StringUtils.isNotBlank(userForm.getCompanyQQ())) {
                String[] qqs = userForm.getCompanyQQ().split(",");
                for (int i = 0; i < qqs.length; i++) {
                    UserContact qq = new UserContact();
                    qq.setContactType(UserContact.CONTACT_TYPE_QQ);
                    qq.setContactAccount(qqs[i]);
                    contacts.add(qq);
                }
            }


            userDetail.setContactList(contacts);


            List<ShippingType> shippingTypes = new ArrayList<ShippingType>();

            userDetail.setShippingTypes(userForm.getCompanyShippingTypes());


            if (StringUtils.isNotBlank(userForm.getCompanyMajorLines())) {
                List<Location> majorLines = new ArrayList<Location>();
                String[] locations = userForm.getCompanyMajorLines().split(",");
                for (String locationId : locations) {
                    Location location1 = new Location(Integer.parseInt(locationId), null);
                    majorLines.add(location1);
                }
                userDetail.setLines(majorLines);
            }


        } else if (userType == User.USER_TYPE_SENDER) {
            Location location = new Location();
            userDetail.setLocation(userForm.getSenderLocation());

            userDetail.setUserName(userForm.getSenderName());

            //��ϵ��
            List<UserContact> contacts = new ArrayList<UserContact>();
            //��ϵ�绰
            UserContact userContact = new UserContact();
            userContact.setContactType(UserContact.CONTACT_TYPE_MOBILE_PHONE);
            userContact.setContactName(userForm.getSenderName());
            userContact.setContactAccount(userForm.getSenderPhoneNo());
            contacts.add(userContact);


            //QQ
            if (StringUtils.isNotBlank(userForm.getSenderQQ())) {
                String[] qqs = userForm.getSenderQQ().split(",");
                for (int i = 0; i < qqs.length; i++) {
                    UserContact qq = new UserContact();
                    qq.setContactType(UserContact.CONTACT_TYPE_QQ);
                    qq.setContactAccount(qqs[i]);
                    contacts.add(qq);
                }

            }

            userDetail.setContactList(contacts);


            String[] locationIds = userForm.getSenderRegularLine().split(",");
            List<Location> lines = new ArrayList<Location>();
            for (String id : locationIds) {
                try {

                    Location location1 = commonService.getLocationById(Long.parseLong(id));
                    if (location1 != null) {
                        lines.add(location1);
                    }
                } catch (NumberFormatException e) {
                    throw new MyException("常发路线输入错误");
                }
            }
            if(lines.size()>0){
                userDetail.setLines(lines);
            }

        } else {

            userDetail.setLocation(userForm.getOtherLocation());
            userDetail.setUserName(userForm.getOtherName());
            userDetail.setRemark(userForm.getOtherRemark());


            //��ϵ��
            List<UserContact> contacts = new ArrayList<UserContact>();
            //��ϵ�绰
            UserContact userContact = new UserContact();
            userContact.setContactType(UserContact.CONTACT_TYPE_MOBILE_PHONE);
            userContact.setContactName(userForm.getOtherName());
            userContact.setContactAccount(userForm.getOtherPhone());
            contacts.add(userContact);

            //QQ
            if (StringUtils.isNotBlank(userForm.getOtherQQ())) {
                String[] qqs = userForm.getOtherQQ().split(",");
                for (int i = 0; i < qqs.length; i++) {
                    UserContact qq = new UserContact();
                    qq.setContactType(UserContact.CONTACT_TYPE_QQ);
                    qq.setContactAccount(qqs[i]);
                    contacts.add(qq);
                }

            }
            userDetail.setContactList(contacts);


        }

        try {
            userService.addUser(userDetail);
        } catch (UserAlreadyExistsException e) {
            result.rejectValue((String) e.getExtData(), null, e.getMessage());
            return "register";
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException("用户注册失败", ex);
        }

        model.addAttribute("successType", "register");
       return "success";
    }


}
